<template>
	<view class="">
		<view class="cashierDeductionPage">
			<view class="viewDetailsTop flex-column border-bottom-f7f7f7">
				<view class="flex-column  " v-if="!productInformation" style="height: 300rpx;"
					@click="selsectProduct()">

					<uni-icons type="plusempty" size="30"></uni-icons>
					<view class="margin-top_10rpx">
						选择商品
					</view>
				</view>
				<!-- 下单地址 -->
				<view class="orderPageDetail" v-else>
					<view class="orderPageDescribe flex-between">
						<view @click="selsectProduct()">
							<image class="img" :src="productInformation.host_img[0]" mode=""></image>
						</view>
						<view class="flex-column-between margin-left_20rpx" style="height: 232rpx ;width: 66%;">
							<view class="font-overflow2" @click="selsectProduct()">
								{{productInformation.name}}
							</view>

							<view class="font-overflow " @click="selsectProduct()">
								<text style="color: #999999;">{{productInformation.title}}</text>
							</view>


							<view class="flex-start-center">
								<view style="color: rgb(255, 0, 0);">
									￥{{productInformation.price}}
								</view>
								<view class="margin-left_20rpx" style="color: rgb(255, 0, 0);">
									<text>数量x{{Number(form.number)}}</text>
								</view>
							</view>
							<!-- 数量 -->
							<view class="flex-between">
								<view style="margin: 5rpx 0;font-weight: 600;">
									购买数量
								</view>
								<view class="">
									<uni-number-box :min="1" @change="changeNumber"
										v-model="vModelValue"></uni-number-box>
								</view>
							</view>

						</view>

					</view>
					<!-- 优惠券抵扣 -->
					<view class="flex-between Deduction">
						<view class="">
							优惠券
						</view>
						<view style="color: rgb(255, 0, 0);" @click="receiveCoupon()">
							{{discountPrice?'-'+discountPrice+'元' :'选择优惠券'}}
						</view>

					</view>
					<view class="flex-between Deduction">
						<view class="">
							会员折扣
						</view>
						<view style="color: rgb(255, 0, 0);">
							{{discount/10}}折
						</view>
					</view>
					<view class="flex-between Deduction">
						<view class="">
							支付金额
						</view>
						<view style="color: rgb(255, 0, 0);">
							<text
								style="color: rgb(255, 0, 0);font-size: 40rpx;">￥{{finalPrice(productInformation.price*Number(this.form.number),discountPrice)}}</text>
						</view>
					</view>
					<view class="flex-betweens margin-top_16rpx Deduction">
						<view class="flex-start-center-wrap">

							<view class="example-body">

							</view>


						</view>
						<view class="couponCollection flex" @click="couponCollection()">

							<text>领券</text>
							<uni-icons type="right" color="#fff" size="15"></uni-icons>

						</view>
					</view>

				</view>

			</view>
			<view class="paymentMethod" v-if="userInfo">
				<view class="flex-start-center">
					<view class="line">

					</view>
					<view class="margin-left_16rpx font-weight_bold">
						请选择支付方式
					</view>
				</view>
				<view class="margin-left_30rpx margin-top_10rpx" style="color: rgb(42, 137, 255);">
					<text>余额:{{userInfo.balance}} | 积分：{{userInfo.surplus_integral}} </text>
				</view>
				<view class="cashierSelection " v-for="(item, index) in items" :key="item.value">
					<view class=" flex-between ">
						<view class="flex" v-if="!(index==1&&productInformation.buying_pattern==2)">
							<image class="image " :src="item.img" mode=""></image>
							<view class=" margin-left_20rpx">
								{{item.name}}
							</view>
						</view>
						<view class="flex">
							<!-- :localdata="`${index}`" -->
							<text style="margin-right: 20rpx;"
								v-if="index==1&&productInformation.buying_pattern==1">可抵扣{{deduction_integral_ratio?deduction_integral_ratio+'元':0+'元'}}</text>
							<uni-data-checkbox v-if="index==0" multiple :localdata="range"
								@change="e=>radioChange(e,index)"></uni-data-checkbox>
							<uni-data-checkbox v-model="currentIndex"
								v-if="index==1&&productInformation.buying_pattern==1" multiple :localdata="range1"
								@change="e=>radioChange(e,index)"></uni-data-checkbox>
							<!-- <label class="radio" >
								<radio-group @change="radioChange">
									<label class="uni-list-cell uni-list-cell-pd">
										<view>
											<radio style="transform:scale(0.7)" :value="item.value"
												:checked="index == current" />
										</view>
							
									</label>
								</radio-group>
							</label> -->
						</view>
					</view>
				</view>

			</view>
		</view>



		<view class="nextBtn flex" @click="nextPay()">
			支付
		</view>
		<!-- 领取优惠券 -->
		<sunui-popup ref="couponCollectionPopup">
			<template v-slot:content>

				<view class="receiveCouponContain flex-column-Jstart">

					<view class="top flex-between">
						<view class="">

						</view>
						<text>先领券,在购物</text>
						<uni-icons @click='closeCollectionffIcon' class="uniIcon" type="clear" size="30"
							style="color: #07070791;">
						</uni-icons>
					</view>
					<mescroll-body ref="mescrollRef" :height="windowHeight+'rpx'" @init="mescrollInit"
						@down="downCallback" @up="upCallback" :up="upOption" :down="downOption">
						<scroll-view v-if="list.length" :scroll-y="true" style="height: 800rpx;">
							<block v-for="(item,index) in list" :key="index">
								<view class="content ">
									<view class="positionCoupon  flex">
										<text class="font-overflow">{{item.name}}</text>
									</view>
									<view class="couponPrice">
										<view class="flex-between ">
											<view class="flex">
												<view class="left">
													<text style="color: rgb(255, 0, 0)">￥</text>
													<text
														style="color: rgb(255, 0, 0);font-family: Inter;font-size: 64rpx;">{{item.discount_intensity}}</text>
												</view>
												<view class="flex-columns"
													style="height: 77rpx;justify-content: space-between;">
													<text
														style="color: rgb(255, 0, 0);font-size: 28rpx">{{ item.type === 3 ? '无门槛福利优惠券' : '满' + totelName(item.trigger_amount) + '减' +totelName(item.discount_intensity)  + '元' }}</text>
													<text
														style="color:rgb(153, 153, 153);font-size: 24rpx">{{(item.end_time) }}到期
													</text>
												</view>
											</view>
											<view class="claimNow flex" @click="couponCollections(item)">
												立即领取
											</view>
										</view>
									</view>
								</view>

							</block>
						</scroll-view>
					</mescroll-body>
					<view v-if="list.length" class="bottom flex" @click="allCouponCollections()">
						全部领取
					</view>

				</view>

			</template>
		</sunui-popup>
		<!-- 领取优惠券 -->
		<sunui-popup ref="receiveCouponPopup">
			<template v-slot:content>

				<view class="receiveCouponContain flex-column-Jstart">

					<view class="top flex-between">
						<view class="">

						</view>
						<text>选择我的优惠券</text>
						<uni-icons @click='closeWriteOffIcon()' class="uniIcon" type="clear" size="30"
							style="color: #07070791;">
						</uni-icons>
					</view>
					<mescroll-body ref="mescrollRef" :height="windowHeight+'rpx'" @init="mescrollInit"
						@down="downCallback" @up="upCallback" :up="upOption" :down="downOption">
						<scroll-view v-if="list.length" :scroll-y="true" style="height: 800rpx;">
							<block v-for="(item,index) in list" :key="index">
								<view class="content ">
									<view class="positionCoupon  flex">
										<text class="font-overflow">{{item.name}}</text>
									</view>
									<view class="couponPrice">
										<view class="flex-between ">
											<view class="flex">
												<view class="left">
													<text style="color: rgb(255, 0, 0)">￥</text>
													<text
														style="color: rgb(255, 0, 0);font-family: Inter;font-size: 64rpx;">{{totelName(item.discount_intensity)}}</text>
												</view>
												<view class="flex-columns"
													style="height: 77rpx;justify-content: space-between;">
													<text
														style="color: rgb(255, 0, 0);font-size: 28rpx">{{ item.type === 3 ? '无门槛福利优惠券' : '满' + totelName(item.trigger_amount) + '减' +totelName(item.discount_intensity)  + '元' }}</text>
													<text
														style="color:rgb(153, 153, 153);font-size: 24rpx">{{extractedDate(item.effective_time) }}到期
													</text>
												</view>
											</view>
											<view class="claimNow flex" @click="receiveCoupons(item,index)">
												{{selectCouponIndex==index?'取消选择':'立即选择'}}
											</view>
										</view>
									</view>
								</view>
							</block>
						</scroll-view>
					</mescroll-body>


				</view>

			</template>
		</sunui-popup>
	</view>
</template>

<script>
	export default {
		components: {

		},
		data() {
			return {
				currentIndex: '',
				// currentIndex:[],
				tabIndex: 4,
				current: 0,

				items: [{


						value: '0',
						name: '余额支付',
						checked: 'true',
						img: '../../../static/会员卡管理端/微信图片_20240409092118.png'
					},
					{


						value: '1',
						name: '抵扣积分',
						checked: 'true',
						img: '../../../static/会员卡管理端/微信图片_20240409092134.png'
					}


				],
				vModelValue: 1,
				deductionType: null,
				discountPrice: '',
				discount: '',
				downOption: {
					auto: false
				},
				range: [{
						"value": 0,
					},


				],
				range1: [{
						"value": 1,
					},


				],
				// 选择优惠券索引
				selectCouponIndex: 100,
				// 上拉配置项
				upOption: {
					auto: true
				},
				token: uni.getStorageSync('login').token,
				windowHeight: '',
				list: [],
				form: {
					id: '',


					// // 抵扣类型
					// deductionType: "0",
					number: 1,
					amount: '',
					coupon_id: ''
				},
				productInformation: null,
				deduction_integral_ratio: null,
				isPay: false,
				userInfo: null,
				points_offset: 0,
				// 是否领券
				isCouponCollection: false
			}
		},

		onLoad(options) {
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight * 2 - 800;
				},

			});
			console.log(options)
			// 0 消费扣款 1 余额充值 2开通套餐卡


			// this.$sun.assignObject(this.form, {
			// 	...options
			// })

			// this.deductionType = options
			this.getUserInfo(options.uid)


		},
		onHide() {
			console.log('出发')
			this.productInformation = {}
		},
		onUnload() {
			console.log('出发')
			this.productInformation = {}
		},
		onShow() {
			this.mescroll?.resetUpScroll();
			this.$at.releaseKey('submitAll');
			this.$at.releaseKey('submitPay');
			this.$at.releaseKey('submit');
			if (uni.getStorageSync('shoplDetails')) {
				console.log(uni.getStorageSync('shoplDetails'))
				this.productInformation = uni.getStorageSync('shoplDetails')
				this.init()
			}
		},
		computed: {
			finalPrice: function() {
				return function(price, couponPrice) {
					let result
					console.log(price, couponPrice)
					result = (Math.floor(price * Number(this.discount)) / 100).toFixed(2)
					// result = (price * this.discount) / 100
					if (this.productInformation.buying_pattern == 1) {
						result = (result - couponPrice) - this.deduction_integral_ratio;
						console.log(result)
					} else {
						result = result - couponPrice;
					}

					if (result < 0) {
						if (this.productInformation.buying_pattern == 1) {
							console.log(price)

							// 如果没有用优惠券那么就是 
							if (couponPrice) {
								this.deduction_integral_ratio = this.deduction_integral_ratio - Math.abs(result)
							} else {
								this.deduction_integral_ratio = price
							}
						}

					}
					// result = result - couponPrice;
					this.form.amount = Math.max(0.01, result.toFixed(2))

					return Math.max(0.01, result.toFixed(2));
				};


			},
			extractedDate: function() {
				return function(time) {

					return time.split(' ')[0];
				};
			},
			totelName: function() {
				return function(nums) {
					let num
					if (nums.endsWith(".00")) {
						num = nums.slice(0, -3); // 去除末尾的 ".00"
					}
					if (nums >= 10000) {
						let remainder = num % 10000;
						let quotient = Math.floor(num / 10000);
						let decimal = Math.floor(remainder / 1000);
						return quotient + '.' + decimal + '万';
					} else {
						console.log(nums)
						return num ? num : nums;
					}
				};
			},
		},
		methods: {
			async getUserInfo(userId) {


				const ress = await this.$http.post({
					url: this.$api.userinfo,
					data: {

						uid: userId

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				console.log(ress)
				if (ress.code == 0) {

					this.userInfo = ress.data

					// 跳转到登录页面

					// this.$sun.toast(ress.msg, 'none')
					this.init()



				} else {

					this.$sun.toast(ress.msg, 'none')
				}

			},
			closeWriteOffIcon() {
				this.$refs.receiveCouponPopup.close()
			},
			closeCollectionffIcon(){
				this.$refs.couponCollectionPopup.close()
			},
			nextPay() {

				if (!this.isPay) {
					this.$sun.toast('请勾选余额支付', 'none')
					return
				}
				if (!this.productInformation) {
					this.$sun.toast('请选择商品', 'none')
					return
				} else {

					this.$at.uniDoFunc({
						key: 'submitPay',
						success: async () => {
							this.$at.lockKey('submitPay');
							// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
							console.log(this.form)
							this.$at.releaseKey('submitPay');
							const result = await this.$http.post({
								url: this.$api.createGoodsOrder,
								data: {
									goods_id: this.productInformation.id,
									uid: this.userInfo.id,
									coupon_id: this.form.coupon_id,
									number: this.form.number,
									payway: 1,
									random_code: this.userInfo.random_code,
									points_offset: this.points_offset

								},
								headers: {
									'Authorization': `Bearer ${this.token}`
								}

							})
							if (result.code == 0) {
								this.$sun.toast(result.msg, 'none')
								this.$at.releaseKey('submitPay');
								setTimeout(() => {
									this.$sun.navBack()
								}, 1000)
							} else {
								this.$sun.toast(result.msg, 'none')
								this.$at.releaseKey('submitPay');

							}



						}
					});

				}
			},
			async init() {

				const result = await this.$http.post({
					url: this.$api.gooodsDiscount,
					data: {
						goods_id: this.productInformation.id,
						uid: this.userInfo.id

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {

					this.discount = result.data.discount
				} else {
					this.$sun.toast(result.msg, 'none')
				}

			},
			receiveCoupons(item, index) {
				if (this.selectCouponIndex == index) {
					console.log('取消选择', this.selectCouponIndex, index)
					this.selectCouponIndex = 100
					this.discountPrice = ''
					this.form.coupon_id = ''
				} else {
					if (item.type !== 3 && this.productInformation.price * Number(this.form.number) < item
						.trigger_amount) {
						this.$sun.toast('优惠券不满足当前状态', 'none')
						return
					} else {
						this.selectCouponIndex = index

						this.form.coupon_id = item.id
						console.log(item)
						// 这里需要判断当前的余额是否大于优惠卷 如果优惠券大于余额不可以折扣（前提是满减券和新人券）


						this.discountPrice = item.discount_intensity
					}

				}
				this.$refs.receiveCouponPopup.close()

			},
			couponCollections(item){
				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
				
				
				
						const result = await this.$http.post({
							url: this.$api.receiveCoupon,
							data: {
								id: [item.id],
								uid:this.userInfo.id,
							},
							headers: {
								'Authorization': `Bearer ${this.token}`
							}
				
						})
				
						if (result.code == 0) {
				
				
							this.$at.releaseKey('submit');
				
				
							this.$sun.toast(result.msg, 'none')
							// this.$sun.toast(resPoster.msg, 'none')
							setTimeout(() => {
								this.mescroll?.resetUpScroll();
							}, 500)
				
						} else {
							this.$at.releaseKey('submit');
							this.$sun.toast(result.msg, 'none')
						}
				
				
					}
				});
			},
			allCouponCollections(){
				this.$at.uniDoFunc({
					key: 'submitAll',
					success: async () => {
						this.$at.lockKey('submitAll');
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
				
						const idArr = this.list.map((item) => {
							return item.id
						})
						console.log(idArr)
						const result = await this.$http.post({
							url: this.$api.receiveCoupon,
							data: {
								id: idArr,
								uid:this.userInfo.id,
							},
							headers: {
								'Authorization': `Bearer ${this.token}`
							}
				
						})
				
						if (result.code == 0) {
				
				
							this.$at.releaseKey('submitAll');
				
				
							this.$sun.toast(result.msg, 'none')
							// this.$sun.toast(resPoster.msg, 'none')
							setTimeout(() => {
								this.mescroll?.resetUpScroll();
							}, 500)
				
						} else {
							this.$at.releaseKey('submitAll');
							this.$sun.toast(result.msg, 'none')
						}
				
				
					}
				});
			},
			selsectProduct() {
				this.$sun.navGo('/pages/cashierSystem/detailsProduct/detailsProduct')
			},
			// 改变数字
			changeNumber(num) {
				console.log(num)
				this.form.number = num
				this.currentIndex = [100]
				this.points_offset = 0
				this.deduction_integral_ratio = 0

			},
			async radioChange(e, index) {
				console.log(e)
				if (e.detail.data.length) {


					if (e.detail?.data[0]?.value == 1) {
						console.log('开启')
						this.points_offset = 1
						this.current = e.detail.value
						// 获取积分进行抵扣
						const res = await this.$http.post({
							url: this.$api.getConfig,
							data: {


							},
							headers: {
								'Authorization': `Bearer ${this.token}`
							}

						})
						console.log(res)
						if (res.code == 0) {
							const ress = res.data.deduction_integral_ratio
							// console.log(ress)    (Math.floor(price* Number(this.discount)) / 100).toFixed(2)
							this.deduction_integral_ratio = (Math.floor((Number(this.userInfo.surplus_integral) /
									Number(ress)) *
								100) / 100).toFixed(2);
							console.log(this.deduction_integral_ratio)
						} else {
							this.$sun.navGo(res.msg, 'none')
						}
					} else {

						this.isPay = true

					}
				} else {

					if (e.detail.data.length == 0 && index == 1) {
						console.log('关闭')
						this.points_offset = 0
						this.deduction_integral_ratio = 0
					} else {
						this.isPay = false
					}
				}




			},

			// 选择优惠券
			receiveCoupon() {
				this.isCouponCollection = false

				this.$refs.receiveCouponPopup.show({
					anim: 'bottom',
					position: 'bottom',
					shadeClose: false, //false使用户不能点击其它关闭页面
					topclose: false,
					zIndex: 99999
				});

			},
			couponCollection() {
				this.isCouponCollection = true
				// 领券
				this.$refs.couponCollectionPopup.show({
					anim: 'bottom',
					position: 'bottom',
					shadeClose: false, //false使用户不能点击其它关闭页面
					topclose: false,
					zIndex: 99999
				});
			},

			async upCallback(scroll) {
				let coupon = this.isCouponCollection ? this.$api.userAuthorityCoupon : this.$api.userCouponList
				let form
				if (this.isCouponCollection) {
					form = {
						uid: this.userInfo.id,
						page: scroll.num,
						limit: 10
					}
				} else {
					form = {
						uid: this.userInfo.id,
						classify_id: this.productInformation.classify_id
					}
				}
				const result = await this.$http.post({
					url: coupon,
					data: {

                      ...form

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})
				if (result.code == 0) {

					console.log('地址管理列表', this.productInformation);
					// 判断当前 商品分类id 和我们的优惠券id是否相等（包括分类id为0） 
					this.mescroll.endByPage(result.data.list.length, this.$sun.pagingSum(result.data.count, 10));
					if (scroll.num == 1) this.list = [];
					this.list = this.list.concat(result.data.list);
					this.list = this.list.filter((item) => {
						return item.classify_id == this.productInformation.classify_id || item.classify_id ==
							0;
					})
					console.log('this.list', this.list, this.list.length);
				}
			},
		}
	}
</script>

<style lang="less" scoped>
	.receiveCouponContain {
		background-color: #fff;
		height: auto;
		overflow: auto;



		.top {


			padding: 30rpx 0;
			width: 100%;

			text {
				color: rgb(0, 0, 0);
				font-size: 36rpx;
				font-weight: 400;
			}
		}

		.content {

			width: 698rpx;
			height: auto;
			overflow-x: auto;
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			background: rgb(255, 242, 242);

			.positionCoupon {
				padding: 8rpx;
				width: 154rpx;
				height: 50rpx;
				border-radius: 20rpx 0rpx 20rpx 0rpx;
				color: rgb(255, 0, 0);
				background: rgb(255, 219, 219);
				font-size: 24rpx;
			}

			.couponPrice {
				padding: 20rpx 26rpx;

				.left {
					margin-right: 32rpx;
				}

				.claimNow {
					width: 144rpx;
					height: 58rpx;
					border-radius: 25rpx;
					color: #fff;
					background: rgb(255, 0, 0);
				}
			}
		}




		.bottom {

			border-radius: 600rpx;
			width: 662rpx;
			height: 96rpx;
			box-shadow: 0px 4px 4px 0px rgba(28, 197, 45, 0.2);
			background: rgb(255, 0, 0);
			color: #fff;
			position: fixed;
			bottom: 20rpx;
		}
	}






	.nextBtn {
		position: fixed;
		bottom: 20rpx;
		width: 90%;
		height: 96rpx;
		background: rgb(0, 87, 254);
		color: rgb(255, 255, 255);
		margin-left: 40rpx;
	}

	.cashierDeductionPage {
		.viewDetailsTop {
			width: 750rpx;
			padding: 40rpx 0;
			background: rgb(255, 255, 255);

			.avatar {
				width: 116rpx;
				height: 116rpx;
			}

			.orderPageDetail {
				margin-top: 20rpx;
				padding: 40rpx;
				width: 100%;
				background: rgb(255, 255, 255);

				.orderPageDescribe {
					// padding-right: 90rpx;

					.img {
						width: 230.02rpx;
						height: 232rpx;
					}


				}

				.Deduction {
					margin-top: 46rpx;
				}
			}

			.couponCollection {
				padding-left: 15rpx;
				color: #fff;
				width: 110rpx;
				height: 48rpx;
				border-radius: 100px;
				background: rgb(255, 57, 38);

				.arrow {
					width: 26.86rpx;
					height: 26.88rpx;
				}
			}

		}

		.paymentMethod {
			.line {
				width: 6px;
				height: 16px;
				background: rgb(42, 137, 255);
			}

			margin-top: 30rpx;
			padding: 40rpx;
			background: rgb(255, 255, 255);
		}

		.cashierSelection {

			padding: 30rpx;

			/deep/.checklist-box {
				margin-right: 0 !important;
			}

			.image {
				width: 56rpx;
				height: 56rpx;
			}

			background: rgb(255, 255, 255);
		}

		.cashierSelectionContent {
			margin-top: 10rpx;
			padding: 30rpx;
			width: 332.96rpx;
			height: 171.56rpx;

			background: rgb(255, 246, 246);
		}

		.cashierSelectionContent-noActive {
			margin-top: 10rpx;
			padding: 30rpx;
			width: 332.96rpx;
			height: 171.56rpx;

			box-sizing: border-box;
			border: 2rpx solid rgb(228, 227, 227);
			background: rgb(255, 255, 255);
		}

		.viewDetails {
			background: rgb(255, 255, 255);
		}
	}

	page {
		background: #f6f6f6;
	}
</style>